<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    :minHeight="300"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <FormTitle text="基础设置" class="ml-4" />
    <div class="ml-1 mt-2">
      <BasicForm @register="registerForm" @field-value-change="handleChangeFeild" />
    </div>
    <div class="componentConfig" v-if="isUploadType(componentType)">
      <FormTitle text="数据源设置" class="ml-4 mb-2" />
      <BasicForm @register="registerUploadForm" />
    </div>
    <div class="componentConfig" v-if="isSubTableType(componentType) && dataSourceType">
      <FormTitle text="数据源设置" class="ml-4 mb-2" />
      <SubTableConfig ref="subTableRef" :sourceType="dataSourceType" />
    </div>
    <div class="componentConfig" v-if="isOptionsType(componentType)">
      <div class="py-4" v-if="dataSourceType === DATA_SOURCE_TYPE_TYPE">
        <FormTitle text="数据源设置" class="ml-4" />
        <CommonConfig
          class="pl-9"
          :data="selectOptions"
          @add="handleAddCustomOption()"
          @del="handleDelMutilCustomOption"
          @del-mutil="handleDelMutilCustomOption"
        />
      </div>

      <div class="py-4" v-else-if="dataSourceType !== DATA_API_SOURCE_TYPE">
        <FormTitle text="SQL定义" class="ml-4" />
        <div class="mt-4 ml-1">
          <BasicForm @register="registerSQLForm" />
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import CommonConfig from './CommonConfig.vue';
  import FormTitle from './FormTitle.vue';
  import SubTableConfig from './sub-table/SubTableConfig.vue';
  import { SubTableInstance } from './sub-table/subTable.data';

  import { cloneDeep } from 'lodash-es';
  import { DICT } from '/@/enums/dict';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDictTypeListApi } from '/@/api/admin/dict';
  import { formItemSchema, SQLTableSchema, uploadSchema } from './title.data';
  import {
    OPTIONS_TYPE,
    DATA_SOURCE_TYPE_TYPE,
    DATA_DICT_TYPE,
    DATA_API_SOURCE_TYPE,
  } from './consts';
  import { ComponentTypeEnum } from '/@/components/ModelTable/src/types';
  import { toJson } from '/@/utils';
  // const isSubTable = ({ values }) => values.componentType === ComponentTypeEnum.SubTable;

  export default defineComponent({
    name: 'FormTitleConfigModal',
    components: { BasicModal, BasicForm, CommonConfig, FormTitle, SubTableConfig },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const updateInfo = ref<any>({
        isUpdate: false,
      });

      const { createMessage } = useMessage();

      const componentType = ref();
      const dataSourceType = ref();
      const selectOptions = ref<any>([]);
      const subTableRef = ref<Nullable<SubTableInstance>>(null);

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 120,
        baseColProps: { lg: 11, md: 23 },
        schemas: formItemSchema,
        showActionButtonGroup: false,
      });

      const [registerSQLForm, { resetSchema, setFieldsValue: setSQLFields, validate: SQLValid }] =
        useForm({
          labelWidth: 120,
          baseColProps: { lg: 7, md: 24 },
          schemas: SQLTableSchema(unref(componentType)),
          showActionButtonGroup: false,
        });

      const [registerUploadForm, { setFieldsValue: setUploadFields, validate: UploadValid }] =
        useForm({
          labelWidth: 120,
          baseColProps: { lg: 12, md: 24 },
          schemas: uploadSchema,
          showActionButtonGroup: false,
        });
      async function init(data: Indexable) {
        componentType.value = '';
        updateInfo.value = {
          isUpdate: !!data?.isUpdate,
          index: data?.record?.index,
          record: cloneDeep(data?.record || {}),
        };
        if (!!data?.isUpdate) {
          const comProps = data?.record.componentProps;
          setFieldsValue({
            ...data?.record,
            props: JSON.stringify(comProps),
          });
          const comType = data.record.componentType;
          componentType.value = comType;
          dataSourceType.value = data.record.dataSourceType;

          if (data?.record.componentProps) {
            const { options } = data?.record.componentProps;
            selectOptions.value = options || [];
          }

          // 需要数据源选项
          if (isOptionsType(comType)) {
            nextTick(() => {
              resetSchema(SQLTableSchema(comType));
              data.record.dataForm && setSQLFields(data.record.dataForm);
            });
          }
          // 上传组件数据源字段
          if (isUploadType(comType)) {
            nextTick(() => {
              data.record.attachment && setUploadFields(data.record.attachment);
            });
          }
          if (isSubTableType(comType)) {
            nextTick(() => {
              subTableRef.value!.setValues(data.record.simpleChildTable || {});
            });
          }
        }

        let type = DICT.COMPONENT_TYPE;
        if (data.client === 1) {
          type = DICT.APP_COMPONENT_TYPE;
        }
        updateSchema({
          field: 'componentType',
          componentProps: {
            params: {
              type,
            },
          },
        });
      }

      const [registerDrawer, { setModalProps, closeModal, scrollBottom }] = useModalInner(
        async (data: Indexable) => {
          resetFields();
          setModalProps({ confirmLoading: false });
          init(data);
        },
      );

      const getTitle = computed(() => (!unref(updateInfo).isUpdate ? '新增' : '编辑'));

      function handleChangeFeild(key, val) {
        switch (key) {
          case 'componentType':
            componentType.value = val;

            if (isOptionsType(val)) {
              setFieldsValue({ dataSourceType: undefined });
              updateSchema({ field: 'dataSourceType' });
              unref(dataSourceType) !== DATA_SOURCE_TYPE_TYPE && resetSchema(SQLTableSchema(val));
            }
            break;
          case 'dataSourceType':
            dataSourceType.value = val;
            selectOptions.value = [];
            break;

          default:
            break;
        }
      }

      // scrollTop
      async function modelScroll() {
        setTimeout(async () => {
          scrollBottom && (await scrollBottom());
        }, 100);
      }
      const handleAddCustomOption = () => {
        const optionItem = {
          field: '',
          op: '=',
          label: '',
          value: '',
          labelType: '',
        };
        selectOptions.value.push(optionItem);
        modelScroll();
      };

      const handleDelMutilCustomOption = (arr) => {
        selectOptions.value = arr || [];
      };

      async function handleSubmit() {
        try {
          const values = await validate();
          let dataForm = {};
          if (
            isOptionsType(values.componentType) &&
            values.dataSourceType !== DATA_SOURCE_TYPE_TYPE
          ) {
            dataForm = await SQLValid();
            selectOptions.value = [];
          }
          let attachment = {};
          if (isUploadType(values.componentType)) {
            attachment = await UploadValid();
          }
          let simpleChildTable = {};
          if (isSubTableType(values.componentType)) {
            const ret = await subTableRef.value!.getValues();

            simpleChildTable = ret;
          }

          setModalProps({ confirmLoading: true });

          const params = Object.assign(unref(updateInfo).record, values, {
            dataForm,
            attachment,
            simpleChildTable,
          });
          if (!params.componentProps) {
            params.componentProps = {};
          }
          if (params.props) {
            params.componentProps = toJson(params.props);
          }

          if (isOptionsType(params.componentType)) {
            params.componentProps.options = selectOptions.value;
          } else {
            params.componentProps.options = [];
          }

          createMessage.success('操作成功', 0.8);
          closeModal();
          updateInfo.value.record = params;
          emit('success', updateInfo.value);
          params.component = ComponentTypeEnum[params.componentType];
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      function handleCancel() {
        // updateInfo.value.isUpdate && emit('success', unref(updateInfo));
      }
      function isOptionsType(comType: ComponentTypeEnum) {
        return OPTIONS_TYPE.includes(comType) && dataSourceType.value !== DATA_DICT_TYPE;
      }
      function isUploadType(comType: ComponentTypeEnum) {
        return comType === ComponentTypeEnum.Upload;
      }
      function isSubTableType(comType: ComponentTypeEnum) {
        return comType === ComponentTypeEnum.SubTable;
      }

      return {
        DICT,
        getTitle,
        dataSourceType,
        OPTIONS_TYPE,
        DATA_SOURCE_TYPE_TYPE,
        DATA_API_SOURCE_TYPE,
        componentType,
        selectOptions,
        subTableRef,
        handleCancel,
        handleSubmit,
        isUploadType,
        isOptionsType,
        registerDrawer,
        registerForm,
        isSubTableType,
        registerSQLForm,
        registerUploadForm,
        handleChangeFeild,
        getDictTypeListApi,
        handleAddCustomOption,
        handleDelMutilCustomOption,
      };
    },
  });
</script>
